const express = require("express");
const apiRouter = express.Router();
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const ExcelJS = require("exceljs");
const readData = require("../db/module/readData");
const delData = require("../db/module/delData");
const { saveFileData } = require("../models/middleware"); //文件上传保存文件的中间件

const upload = multer({ dest: "uploads/" }); //文件上传的位置
// 文件存储位置
const filePath = path.join(__dirname, "../uploads/");

// 保存文件的中间件
// let saveFileData = async (req, res, next) => {
//   try {
//     let fileName = decodeURIComponent(req.file.originalname);

//     let result = await writeData(
//       {
//         fileName: req.file.originalname,
//         fileSize: (req.file.size / 1024 / 1024).toFixed(2) + "MB",
//         fileType: req.file.mimetype,
//         filePath: req.file.path,
//         fileId: req.file.filename,
//         createTime: new Date().toLocaleString(),
//       },
//       "fileList"
//     );
//     if (result.code == 20000) {
//       next();
//     } else {
//       res.send({
//         code: 50000,
//         msg: "图片上传失败，请联系管理员",
//       });
//     }
//   } catch (error) {
//     res.send({
//       code: 50000,
//       msg: "系统异常",
//     });
//   }
// };

// 获取文件工作表
apiRouter.post(
  "/getFileSheet",
  upload.single("file"),
  saveFileData,
  async (req, res) => {
    try {
      // 检查文件是否上传成功
      if (!req.file) {
        return res.status(400).send("No file uploaded.");
      }


      const workbook = new ExcelJS.Workbook(); //创建工作簿对象

      // 读取文件
      await workbook.xlsx.readFile(filePath + req.file.filename); //读取文件

      let sheetNames = workbook.worksheets.map((sheet) => sheet.name);

      res.send({
        code: 20000,
        msg: "获取文件工作表成功",
        data: sheetNames,
        fileId: req.file.filename,
      });
    } catch (error) {
      res.send({
        code: 50000,
        msg: "获取文件工作表失败",
        data: [],
      });
    }
  }
);

// 将文件转为json
apiRouter.get("/fileToJson", async (req, res) => {
  try {
    const query = req.query;

    if (!query.fileId) {
      res.send({
        code: 50000,
        msg: "操作失败,请传入文件id",
        data: [],
      });
      return;
    }
    const workbook = new ExcelJS.Workbook(); //创建工作簿对象

    // 读取文件
    await workbook.xlsx.readFile(filePath + query.fileId); //读取文件

    let worksheet = workbook.getWorksheet(query.sheetName);

    let sheets = [];
    worksheet.eachRow((row, rowNumber) => {
      const rowData = row.values;
      sheets.push(rowData);
    });

    let data = [];
    // 转json
    sheets.forEach((item) => {
      let obj = {};

      item.forEach((item2, index) => {
        if (index != 0) {
          obj["key" + index] = item2;
        }
      });
      data.push(obj);
    });

    res.send({
      code: 20000,
      msg: "获取文件工作表成功",
      data: data,
    });
  } catch (error) {
    res.send({
      code: 50000,
      msg: "error",
      data: [],
    });
  }
});

// 获取所有上传过的文件
apiRouter.post("/getUploadedFiles", async (req, res) => {
  try {
    const params = req.body;

    let result = await readData(params, "fileList");

    if (result.code == 20000) {
      // 出预览图片
      result.data.forEach((item) => {
        if (item.fileType.includes("image")) {
          let file = fs
            .readFileSync(filePath + item.fileId)
            .toString("base64");
          item.imageBase64 = "data:image/*;base64," + file || null;
        }
      });
      res.send(result);
    } else {
      res.send({
        code: 50000,
        msg: "获取文件列表失败",
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: "系统异常",
    });
  }
});

// 删除残留文件
apiRouter.get("/deleteFile", async (req, res) => {
  const query = req.query;
  try {
    let result = await delData(
      { fileId: query.fileId, id: query.id },
      "fileList"
    );
    if (result.code == 20000) {
      fs.unlinkSync(filePath + query.fileId);
      res.send({
        code: 20000,
        msg: "删除文件成功",
      });
    }
  } catch (error) {

    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 下载残留的文件
apiRouter.get("/doneFile", (req, res) => {

  const { fileId } = req.query;
  if (!fileId) {
    return res.status(400).send({ code: 40000, msg: "缺少 fileId 参数" });
  }

  const filePath = path.join(filePath, fileId);
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      return res.status(404).send({ code: 40400, msg: "文件未找到" });
    }

    // 根据文件扩展名设置 Content-Type
    const extname = path.extname(fileId);
    let contentType;
    switch (extname) {
      case ".xlsx":
        contentType =
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        break;
      case ".docx":
        contentType =
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        break;
      case ".pdf":
        contentType = "application/pdf";
        break;
      default:
        // 如果不是已知的文件类型，可以返回一个错误或默认类型（这里选择返回错误）
        contentType =
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        break;
    }

    // 设置响应头
    res.type(contentType);
    // 如果需要提示用户下载文件，可以添加 Content-Disposition 头部
    res.setHeader(
      "Content-Disposition",
      `attachment; filename*=utf-8''123.xlsx`
    );

    // 创建可读流并返回给客户端
    const readStream = fs.createReadStream(filePath);

    // 处理文件读取错误
    readStream.on("error", (error) => {
      console.error("文件读取错误:", error);
      res.status(500).send({ code: 50000, msg: "文件读取失败" });
    });

    // 将可读流的内容发送到响应中
    readStream.pipe(res);
  });
});

// 上传图片
apiRouter.post(
  "/uploadImages",
  upload.single("file"),
  saveFileData,
  (req, res) => {
    try {
      let image =
        "data:image/*;base64," +
        fs.readFileSync(filePath + req.file.filename).toString("base64");




      res.send({
        code: 20000,
        data: image,
      });
    } catch (error) {
      res.send({
        code: 50000,
        msg: "上传图片失败" + error.message,
      });
    }
  }
);

// 将文件数据保存在数据库，然后返回文件id
apiRouter.post(
  "/saveFileData",
  upload.single("file"),
  saveFileData,
  async (req, res) => {
    // 获取base64
    let imageBase64 =
      "data:image/*;base64," +
      fs.readFileSync(filePath + req.file.filename).toString("base64");
    res.send({
      code: 20000,
      msg: "上传成功",
      data: {
        fileName: req.file.originalname,
        fileSize: (req.file.size / 1024 / 1024).toFixed(2) + "MB",
        fileType: req.file.mimetype,
        filePath: req.file.path,
        fileId: req.file.filename,
        createTime: new Date().toLocaleString(),
        imageBase64: imageBase64,
      },
    });
  }
);

module.exports = apiRouter;
